{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 机器学习练习 4 - 神经网络"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本章代码涵盖了基于Python的解决方案，用于Coursera机器学习课程的第四个编程练习。 请参考[练习文本](ex4.pdf)了解详细的说明和公式。\n",
    "\n",
    "代码修改并注释：黄海广，haiguang2000@qq.com"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对于这个练习，我们将再次处理手写数字数据集，这次使用反向传播的前馈神经网络。 我们将通过反向传播算法实现神经网络成本函数和梯度计算的非正则化和正则化版本。 我们还将实现随机权重初始化和使用网络进行预测的方法。\n",
    "\n",
    "由于我们在练习3中使用的数据集是相同的，所以我们将重新使用代码来加载数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from scipy.io import loadmat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'X': array([[ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "        [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "        [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "        ..., \n",
       "        [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "        [ 0.,  0.,  0., ...,  0.,  0.,  0.],\n",
       "        [ 0.,  0.,  0., ...,  0.,  0.,  0.]]),\n",
       " '__globals__': [],\n",
       " '__header__': b'MATLAB 5.0 MAT-file, Platform: GLNXA64, Created on: Sun Oct 16 13:09:09 2011',\n",
       " '__version__': '1.0',\n",
       " 'y': array([[10],\n",
       "        [10],\n",
       "        [10],\n",
       "        ..., \n",
       "        [ 9],\n",
       "        [ 9],\n",
       "        [ 9]], dtype=uint8)}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = loadmat('ex4data1.mat')\n",
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于我们以后需要这些（并将经常使用它们），我们先来创建一些有用的变量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((5000, 400), (5000, 1))"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = data['X']\n",
    "y = data['y']\n",
    "\n",
    "X.shape, y.shape#看下维度"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们也需要对我们的y标签进行一次one-hot 编码。 one-hot 编码将类标签n（k类）转换为长度为k的向量，其中索引n为“hot”（1），而其余为0。 Scikitlearn有一个内置的实用程序，我们可以使用这个。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5000, 10)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.preprocessing import OneHotEncoder\n",
    "encoder = OneHotEncoder(sparse=False)\n",
    "y_onehot = encoder.fit_transform(y)\n",
    "y_onehot.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([10], dtype=uint8),\n",
       " array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.]))"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y[0], y_onehot[0,:]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们要为此练习构建的神经网络具有与我们的实例数据（400 +偏置单元）大小匹配的输入层，25个单位的隐藏层（带有偏置单元的26个），以及一个输出层， 10个单位对应我们的一个one-hot编码类标签。 有关网络架构的更多详细信息和图像，请参阅“练习”文件夹中的PDF。\n",
    "\n",
    "我们需要实现的第一件是评估一组给定的网络参数的损失的代价函数。 源函数在练习文本中（看起来很吓人）。 以下是代价函数的代码。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# sigmoid 函数\n",
    "g 代表一个常用的逻辑函数（logistic function）为S形函数（Sigmoid function），公式为： \\\\[g\\left( z \\right)=\\frac{1}{1+{{e}^{-z}}}\\\\] \n",
    "合起来，我们得到逻辑回归模型的假设函数： \n",
    "\t\\\\[{{h}_{\\theta }}\\left( x \\right)=\\frac{1}{1+{{e}^{-{{\\theta }^{T}}X}}}\\\\] "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def sigmoid(z):\n",
    "    return 1 / (1 + np.exp(-z))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 前向传播函数\n",
    "> (400 + 1) -> (25 + 1) -> (10)\n",
    "\n",
    "<img style=\"float: left;\" src=\"../img/nn_model.png\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def forward_propagate(X, theta1, theta2):\n",
    "    m = X.shape[0]\n",
    "    \n",
    "    a1 = np.insert(X, 0, values=np.ones(m), axis=1)\n",
    "    z2 = a1 * theta1.T\n",
    "    a2 = np.insert(sigmoid(z2), 0, values=np.ones(m), axis=1)\n",
    "    z3 = a2 * theta2.T\n",
    "    h = sigmoid(z3)\n",
    "    \n",
    "    return a1, z2, a2, z3, h"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 代价函数\n",
    "<img style=\"float: left;\" src=\"../img/nn_cost.png\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def cost(params, input_size, hidden_size, num_labels, X, y, learning_rate):\n",
    "    m = X.shape[0]\n",
    "    X = np.matrix(X)\n",
    "    y = np.matrix(y)\n",
    "    \n",
    "    # reshape the parameter array into parameter matrices for each layer\n",
    "    theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\n",
    "    theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\n",
    "    \n",
    "    # run the feed-forward pass\n",
    "    a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\n",
    "    \n",
    "    # compute the cost\n",
    "    J = 0\n",
    "    for i in range(m):\n",
    "        first_term = np.multiply(-y[i,:], np.log(h[i,:]))\n",
    "        second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))\n",
    "        J += np.sum(first_term - second_term)\n",
    "    \n",
    "    J = J / m\n",
    "    \n",
    "    return J"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个Sigmoid函数我们以前使用过。 前向传播函数计算给定当前参数的每个训练实例的假设。 它的输出形状应该与y的一个one-hot编码相同。 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((25, 401), (10, 26))"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 初始化设置\n",
    "input_size = 400\n",
    "hidden_size = 25\n",
    "num_labels = 10\n",
    "learning_rate = 1\n",
    "\n",
    "# 随机初始化完整网络参数大小的参数数组\n",
    "params = (np.random.random(size=hidden_size * (input_size + 1) + num_labels * (hidden_size + 1)) - 0.5) * 0.25\n",
    "\n",
    "m = X.shape[0]\n",
    "X = np.matrix(X)\n",
    "y = np.matrix(y)\n",
    "\n",
    "# 将参数数组解开为每个层的参数矩阵\n",
    "theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\n",
    "theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\n",
    "\n",
    "theta1.shape, theta2.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((5000, 401), (5000, 25), (5000, 26), (5000, 10), (5000, 10))"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\n",
    "a1.shape, z2.shape, a2.shape, z3.shape, h.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "代价函数在计算假设矩阵h之后，应用代价函数来计算y和h之间的总误差。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7.1117081686019654"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cost(params, input_size, hidden_size, num_labels, X, y_onehot, learning_rate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 正则化代价函数\n",
    "我们的下一步是增加代价函数的正则化。  它实际上并不像看起来那么复杂 - 事实上，正则化术语只是我们已经计算出的代价的一个补充。 下面是修改后的代价函数。\n",
    "<img style=\"float: left;\" src=\"../img/nn_regcost.png\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def cost(params, input_size, hidden_size, num_labels, X, y, learning_rate):\n",
    "    m = X.shape[0]\n",
    "    X = np.matrix(X)\n",
    "    y = np.matrix(y)\n",
    "    \n",
    "    # reshape the parameter array into parameter matrices for each layer\n",
    "    theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\n",
    "    theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\n",
    "    \n",
    "    # run the feed-forward pass\n",
    "    a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\n",
    "    \n",
    "    # compute the cost\n",
    "    J = 0\n",
    "    for i in range(m):\n",
    "        first_term = np.multiply(-y[i,:], np.log(h[i,:]))\n",
    "        second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))\n",
    "        J += np.sum(first_term - second_term)\n",
    "    \n",
    "    J = J / m\n",
    "    \n",
    "    # add the cost regularization term\n",
    "    J += (float(learning_rate) / (2 * m)) * (np.sum(np.power(theta1[:,1:], 2)) + np.sum(np.power(theta2[:,1:], 2)))\n",
    "    \n",
    "    return J"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7.1170579556373621"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "cost(params, input_size, hidden_size, num_labels, X, y_onehot, learning_rate)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来是反向传播算法。 反向传播参数更新计算将减少训练数据上的网络误差。 我们需要的第一件事是计算我们之前创建的Sigmoid函数的梯度的函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def sigmoid_gradient(z):\n",
    "    return np.multiply(sigmoid(z), (1 - sigmoid(z)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在我们准备好实施反向传播来计算梯度。 由于反向传播所需的计算是代价函数中所需的计算过程，我们实际上将扩展代价函数以执行反向传播并返回代价和梯度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def backprop(params, input_size, hidden_size, num_labels, X, y, learning_rate):\n",
    "    m = X.shape[0]\n",
    "    X = np.matrix(X)\n",
    "    y = np.matrix(y)\n",
    "    \n",
    "    # reshape the parameter array into parameter matrices for each layer\n",
    "    theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\n",
    "    theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\n",
    "    \n",
    "    # run the feed-forward pass\n",
    "    a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\n",
    "    \n",
    "    # initializations\n",
    "    J = 0\n",
    "    delta1 = np.zeros(theta1.shape)  # (25, 401)\n",
    "    delta2 = np.zeros(theta2.shape)  # (10, 26)\n",
    "    \n",
    "    # compute the cost\n",
    "    for i in range(m):\n",
    "        first_term = np.multiply(-y[i,:], np.log(h[i,:]))\n",
    "        second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))\n",
    "        J += np.sum(first_term - second_term)\n",
    "    \n",
    "    J = J / m\n",
    "    \n",
    "    # add the cost regularization term\n",
    "    J += (float(learning_rate) / (2 * m)) * (np.sum(np.power(theta1[:,1:], 2)) + np.sum(np.power(theta2[:,1:], 2)))\n",
    "    \n",
    "    # perform backpropagation\n",
    "    for t in range(m):\n",
    "        a1t = a1[t,:]  # (1, 401)\n",
    "        z2t = z2[t,:]  # (1, 25)\n",
    "        a2t = a2[t,:]  # (1, 26)\n",
    "        ht = h[t,:]  # (1, 10)\n",
    "        yt = y[t,:]  # (1, 10)\n",
    "        \n",
    "        d3t = ht - yt  # (1, 10)\n",
    "        \n",
    "        z2t = np.insert(z2t, 0, values=np.ones(1))  # (1, 26)\n",
    "        d2t = np.multiply((theta2.T * d3t.T).T, sigmoid_gradient(z2t))  # (1, 26)\n",
    "        \n",
    "        delta1 = delta1 + (d2t[:,1:]).T * a1t\n",
    "        delta2 = delta2 + d3t.T * a2t\n",
    "        \n",
    "    delta1 = delta1 / m\n",
    "    delta2 = delta2 / m\n",
    "    \n",
    "    # unravel the gradient matrices into a single array\n",
    "    grad = np.concatenate((np.ravel(delta1), np.ravel(delta2)))\n",
    "    \n",
    "    return J, grad"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "反向传播计算的最难的部分（除了理解为什么我们正在做所有这些计算）是获得正确矩阵维度。 顺便说一下，你容易混淆了A * B与np.multiply（A，B）使用。 基本上前者是矩阵乘法，后者是元素乘法（除非A或B是标量值，在这种情况下没关系）。\n",
    "无论如何，让我们测试一下，以确保函数返回我们期望的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(7.1170579556373621, (10285,))"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "J, grad = backprop(params, input_size, hidden_size, num_labels, X, y_onehot, learning_rate)\n",
    "J, grad.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们还需要对反向传播函数进行一个修改，即将梯度计算加正则化。 最后的正式版本如下。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def backprop(params, input_size, hidden_size, num_labels, X, y, learning_rate):\n",
    "    m = X.shape[0]\n",
    "    X = np.matrix(X)\n",
    "    y = np.matrix(y)\n",
    "    \n",
    "    # reshape the parameter array into parameter matrices for each layer\n",
    "    theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\n",
    "    theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\n",
    "    \n",
    "    # run the feed-forward pass\n",
    "    a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\n",
    "    \n",
    "    # initializations\n",
    "    J = 0\n",
    "    delta1 = np.zeros(theta1.shape)  # (25, 401)\n",
    "    delta2 = np.zeros(theta2.shape)  # (10, 26)\n",
    "    \n",
    "    # compute the cost\n",
    "    for i in range(m):\n",
    "        first_term = np.multiply(-y[i,:], np.log(h[i,:]))\n",
    "        second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))\n",
    "        J += np.sum(first_term - second_term)\n",
    "    \n",
    "    J = J / m\n",
    "    \n",
    "    # add the cost regularization term\n",
    "    J += (float(learning_rate) / (2 * m)) * (np.sum(np.power(theta1[:,1:], 2)) + np.sum(np.power(theta2[:,1:], 2)))\n",
    "    \n",
    "    # perform backpropagation\n",
    "    for t in range(m):\n",
    "        a1t = a1[t,:]  # (1, 401)\n",
    "        z2t = z2[t,:]  # (1, 25)\n",
    "        a2t = a2[t,:]  # (1, 26)\n",
    "        ht = h[t,:]  # (1, 10)\n",
    "        yt = y[t,:]  # (1, 10)\n",
    "        \n",
    "        d3t = ht - yt  # (1, 10)\n",
    "        \n",
    "        z2t = np.insert(z2t, 0, values=np.ones(1))  # (1, 26)\n",
    "        d2t = np.multiply((d3t, theta2), sigmoid_gradient(z2t))  # (1, 26)\n",
    "        \n",
    "        delta1 = delta1 + (d2t[:,1:]).T * a1t\n",
    "        delta2 = delta2 + d3t.T * a2t\n",
    "        \n",
    "    delta1 = delta1 / m\n",
    "    delta2 = delta2 / m\n",
    "    \n",
    "    # add the gradient regularization term\n",
    "    delta1[:,1:] = delta1[:,1:] + (theta1[:,1:] * learning_rate) / m\n",
    "    delta2[:,1:] = delta2[:,1:] + (theta2[:,1:] * learning_rate) / m\n",
    "    \n",
    "    # unravel the gradient matrices into a single array\n",
    "    grad = np.concatenate((np.ravel(delta1), np.ravel(delta2)))\n",
    "    \n",
    "    return J, grad"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(7.3264766401720607, (10285,))"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "J, grad = backprop(params, input_size, hidden_size, num_labels, X, y_onehot, learning_rate)\n",
    "J, grad.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们终于准备好训练我们的网络，并用它进行预测。 这与以往的具有多类逻辑回归的练习大致相似。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:21: RuntimeWarning: divide by zero encountered in log\n",
      "C:\\anaconda3\\lib\\site-packages\\ipykernel_launcher.py:21: RuntimeWarning: invalid value encountered in multiply\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "     fun: 0.34648873971573946\n",
       "     jac: array([  3.45137403e-04,   2.31929337e-06,  -2.41850602e-06, ...,\n",
       "        -2.66641069e-04,   2.12514869e-04,  -4.37669150e-04])\n",
       " message: 'Max. number of function evaluations reached'\n",
       "    nfev: 250\n",
       "     nit: 19\n",
       "  status: 3\n",
       " success: False\n",
       "       x: array([-0.92927497,  0.01159647, -0.01209253, ..., -3.70653505,\n",
       "       -0.59870645,  0.43449445])"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from scipy.optimize import minimize\n",
    "\n",
    "# minimize the objective function\n",
    "fmin = minimize(fun=backprop, x0=params, args=(input_size, hidden_size, num_labels, X, y_onehot, learning_rate), \n",
    "                method='TNC', jac=True, options={'maxiter': 250})\n",
    "fmin"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于目标函数不太可能完全收敛，我们对迭代次数进行了限制。 我们的总代价已经下降到0.5以下，这是算法正常工作的一个很好的指标。 让我们使用它发现的参数，并通过网络转发，以获得一些预测。\n",
    "\n",
    "让我们使用它找到的参数，并通过网络前向传播以获得预测。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[10],\n",
       "       [10],\n",
       "       [10],\n",
       "       ..., \n",
       "       [ 9],\n",
       "       [ 9],\n",
       "       [ 9]], dtype=int64)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = np.matrix(X)\n",
    "theta1 = np.matrix(np.reshape(fmin.x[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))\n",
    "theta2 = np.matrix(np.reshape(fmin.x[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))\n",
    "\n",
    "a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)\n",
    "y_pred = np.array(np.argmax(h, axis=1) + 1)\n",
    "y_pred"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最后，我们可以计算准确度，看看我们训练完毕的神经网络效果怎么样。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "accuracy = 99.08%\n"
     ]
    }
   ],
   "source": [
    "correct = [1 if a == b else 0 for (a, b) in zip(y_pred, y)]\n",
    "accuracy = (sum(map(int, correct)) / float(len(correct)))\n",
    "print ('accuracy = {0}%'.format(accuracy * 100))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们已经成功地实施了一个基本的反向传播神经网络，并用它来分类手写数字图像。 在下一个练习中，我们将介绍另一个强大的监督学习算法，支持向量机。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
